#-*-coding:utf-8-*-
# Create your views here.
from crm.models import Members
from crm.models import Salesperson
from crm.models import Salesperson_groups #import modles Salesperson_groups huangzy edit
from crm.models import Agent
from crm.models import Furtherinterest
from crm.models import Projects
from crmv2.models import Student
from models import Follow_up,Next_Follow_Date
from crm.models import Sales_record
#from crm.models import Maillist,Maillog
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
#from django import forms
from django.core.paginator import Paginator, InvalidPage
import time,datetime
#from crm.jsondata import JsonResponse

#import os
#now_path=os.path.abspath('.')

"""调用添加用户显示页"""
def adduser (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    """查用Agent列表"""
    agent = Agent.objects.order_by('id')
    """查用Furtherinterest列表"""
    fi = Furtherinterest.objects.order_by('id')
    pj = Projects.objects.order_by('id')
    try:
        p_id=request.session['program']
    except:
        p_id=0
    sales = Salesperson.objects.order_by('id')
    salesgroup = Salesperson_groups.objects.order_by('id')   #add user group huangzy edit
    return render_to_response('adminadduser.html',{'agent':agent,'p_id':int(p_id),'fi':fi,'pj':pj,'sales':sales,'level':request.session['level'],'salesgroup':salesgroup})

"""保存用户信息"""
def saveuserinfo (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.method == 'POST':
            new_data = request.POST.copy()
            new_data['received_emaill']=request.POST.get('received_emaill','0')
            new_data['received_hardcopy']=request.POST.get('received_hardcopy','0')
            new_data['mba']=request.POST.get('mba','0')
            new_data['mpa']=request.POST.get('mpa','0')
            new_data['dba']=request.POST.get('dba','0')
            new_data['attendsess'] = request.POST.get('attendsess','N')
            new_data['men_area'] = request.POST.get('group','1')
            next_follow_date = request.POST.get('next_follow_date','')
            try:
                new_data['name']=new_data['lastname']+','+new_data['firstname']
            except:
                pass
            if new_data['attendsess'] != 'N':
                new_data['attendsess'] = 'Y'
            member_obj=''
            if new_data.has_key('id'):
                member=Members.objects.get(pk=new_data['id'])
                member_obj=member
                member.name=new_data['name']
                member.interlevel=new_data['interlevel']
                member.job_title=new_data['job_title']
                member.company=new_data['company']
                member.tel_h=new_data['tel_h']
                member.tel_o=new_data['tel_o']
                member.tel_m=new_data['tel_m']
                member.email=new_data['email']
                member.address=new_data['address']
                member.received_emaill=new_data['received_emaill']
                member.received_hardcopy=new_data['received_hardcopy']
                member.attendsess=new_data['attendsess']
                member.education=new_data['education']
                member.work_experience=new_data['work_experience']
                member.agent_id=new_data['agent_id']
                member.projects_id=new_data['projects_id']
                member.furtherinterest_id=new_data['furtherinterest_id']
                member.mba=int(new_data['mba'])
                member.mpa=int(new_data['mpa'])
                member.dba=int(new_data['dba'])
                member.message=new_data['message']
                member.men_area = new_data['men_area']
                if request.session['level']=='administrators':
                    #member.salesperson_id=new_data['salesperson_id']
                    #sales_record记录.
                    had_sales_id=member.salesperson_id
                    try:
                        had_sales_id=int(had_sales_id)
                    except:
                        had_sales_id=0
                    if had_sales_id!=int(new_data['salesperson_id']):
                        #如果两个销售ID不同,就意味着改变了,需记录
                        sr_list=Sales_record.objects.filter(members=member)
                        today=datetime.date.today()
                        today=str(today)
                        if sr_list:
                            #原已有记录,直接入库.
                            try:
                                sales_obj=Salesperson.objects.get(pk=new_data['salesperson_id'])
                            except:
                                sales_obj=''
                            lastid=''
                            sr_list=Sales_record.objects.filter(members=member).order_by('-id')[:1]
                            for sr in sr_list:
                                lastid=sr.id
                            if lastid:
                                try:
                                    last_record_obj=Sales_record.objects.get(pk=lastid)
                                except:
                                    last_record_obj=''
                            srinfo=Sales_record(
                            members=member,
                            salesperson=sales_obj,
                            starttime=today,
                            endtime='',
                            )
                            srinfo.save()
                            try:
                                last_record_obj.endtime=today
                                last_record_obj.save()
                            except:
                                pass
                        else:
                            #新记录,要先看原是否已分配有
                            if had_sales_id!=0:
                                try:
                                    sales_obj=Salesperson.objects.get(pk=had_sales_id)
                                    srinfo=Sales_record(
                                    members=member,
                                    salesperson=sales_obj,
                                    starttime=str(member.regtime)[:10],
                                    endtime=today,
                                    )
                                    srinfo.save()
                                except:
                                    pass
                                try:
                                    sales_obj2=Salesperson.objects.get(pk=new_data['salesperson_id'])
                                    srinfo2=Sales_record(
                                    members=member,
                                    salesperson=sales_obj2,
                                    starttime=today,
                                    endtime='',
                                    )
                                    srinfo2.save()
                                except:
                                    pass
                            else:
                                try:
                                    sales_obj2=Salesperson.objects.get(pk=new_data['salesperson_id'])
                                    srinfo2=Sales_record(
                                    members=member,
                                    salesperson=sales_obj2,
                                    starttime=today,
                                    endtime='',
                                    )
                                    srinfo2.save()
                                except:
                                    pass

                    member.salesperson_id=new_data['salesperson_id']
                """如果传过来的STATUS变量值不为空,意味着要添加新的FOLLOW-UP"""
                if new_data['status']!="":
                    finfo=Follow_up(
                    status=new_data['status'],
                    remarks=new_data['remarks'],
                    members_id=new_data['id'],
                    )
                    finfo.save()
                    member.status=new_data['status']
                    member.last_contact=datetime.datetime.now()
                    
                    #如果STATUS为Enrolled则将其添加到student表
                    """
                    if new_data['status']=='7':
                        student = Student.objects.filter(member__id=new_data['id'])
                        if request.session['level']=='administrators':
                            salespersonId=new_data['salesperson_id']
                        else:
                            salespersonId=request.session['id']
                        if len(student)==0:
                            student = Student(
                                        name_en=new_data['name'],
                                        name_ch='',
                                        tel_h=new_data['tel_h'],
                                        tel_o=new_data['tel_o'],
                                        tel_m=new_data['tel_m'],
                                        email=new_data['email'],
                                        address=new_data['address'],
                                        program_id=new_data['projects_id'],
                                        agent_id=new_data['agent_id'],
                                        member_id=new_data['id'],
                                        salesperson_id=salespersonId,
                                      )
                            student.save()
                    """
            else:
                if request.session['level']=='administrators':
                    salesperson_id=new_data['salesperson_id']
                else:
                    salesperson_id=request.session['id']
                member=Members(
                salesperson_id=salesperson_id,
                interlevel=new_data['interlevel'],
                name=new_data['name'],
                job_title=new_data['job_title'],
                company=new_data['company'],
                tel_h=new_data['tel_h'],
                tel_o=new_data['tel_o'],
                tel_m=new_data['tel_m'],
                email=new_data['email'],
                address=new_data['address'],
                received_emaill=new_data['received_emaill'],
                received_hardcopy=new_data['received_hardcopy'],
                attendsess=new_data['attendsess'],
                education=new_data['education'],
                work_experience=new_data['work_experience'],
                agent_id=new_data['agent_id'],
                projects_id=new_data['projects_id'],
                furtherinterest_id=new_data['furtherinterest_id'],
                status='0',
                regtime=datetime.datetime.now(),
                last_contact=datetime.datetime.now(),
                mba=int(new_data['mba']),
                mpa=int(new_data['mpa']),
                dba=int(new_data['dba']),
                message=new_data['message'],
                men_area = new_data['men_area']
                )

            member.save()
            member_obj=member
            #next follow date info
            if next_follow_date!='':
                nd=next_follow_date.split("/")
                next_follow_date=nd[2]+'-'+nd[1]+'-'+nd[0]
                next_follow_date=datetime.date(*[int(i) for i in next_follow_date.split('-')])
            try:
                next_follow_date_obj=Next_Follow_Date.objects.get(member=member_obj,is_removed=0)
                next_follow_date_obj.follow_date=next_follow_date
                next_follow_date_obj.remark=new_data['next_follow_remark']
                next_follow_date_obj.save()
            except:
                if next_follow_date!='':
                    next_follow_date_obj=Next_Follow_Date(
                    member=member_obj,
                    follow_date=next_follow_date,
                    remark=new_data['next_follow_remark'],
                    is_deal=0,
                    is_removed=0,
                    )
                    next_follow_date_obj.save()
            try:            
                return HttpResponseRedirect(new_data['back_url'])
            except:
                return HttpResponseRedirect('/ulist/')
    return HttpResponseRedirect('/ulist/')


"""用户主列表"""
def ulist(request,page='1',kind='',search_id=''):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')

    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')

    members = Members.objects.filter(is_removed=0).order_by('-id')
    if request.session['level']=='sales':
        pass
    else:
        if kind!="":
            if kind=="agent":
                members=members.filter(agent__id=search_id)
            if kind=="sales":
                members=members.filter(salesperson__id=search_id)
        else:
            pass
    try:
        p_id=request.session['program']
    except:
        p_id=0
    if p_id:
        members=members.filter(projects__pk=int(p_id))
        is_p='y'
    else:
        is_p=''
    members_list=apage_list=temp_list=[]
    today=datetime.date.today()
    #startid=30*(int(page)-1)
    #endid=30*int(page)
    paginator=Paginator(members,30)
    #temp_list=members[startid:endid]
    page=int(page)
    curPage = paginator.page(page)
    #members_list=members

    #####################################
    #today's next follow date list
    today=datetime.date.today()
    nf_list=[]
    p_obj=''
    if p_id:
        try:
            p_obj=Projects.objects.get(pk=p_id)
        except:
            p_obj=''
    if request.session['level']=='sales':
        try:
            sales_obj=Salesperson.objects.get(pk=request.session['id'])
            nf_list=Next_Follow_Date.objects.filter(member__salesperson=sales_obj,is_removed=0,is_deal=0,follow_date=today,member__projects=p_obj).order_by('follow_date')
        except:
            pass
    else:
        nf_list = Next_Follow_Date.objects.filter(is_removed=0,follow_date=today,is_deal=0,member__projects=p_obj).order_by('follow_date')
        if kind!="":
            if kind=="sales":
                try:
                    sales_obj=Salesperson.objects.get(pk=int(search_id))
                    nf_list=nf_list.filter(member__salesperson=sales_obj)
                except:
                    pass
    inpage_list=[]
    for nf in nf_list:
        m=nf.member
        m_dict={}
        m_dict['id']=m.id
        inpage_list.append(m.id)
        m_dict['is_today_follow']=1
        try:
            m_dict['salesperson']=m.salesperson
        except:
            m_dict['salesperson']=''
        m_dict['interlevel']=m.interlevel
        m_dict['name']=m.name
        m_dict['job_title']=m.job_title
        m_dict['company']=m.company
        m_dict['tel_h']=m.tel_h
        m_dict['tel_o']=m.tel_o
        m_dict['tel_m']=m.tel_m
        m_dict['email']=m.email
        m_dict['address']=m.address
        m_dict['regtime']=m.regtime
        m_dict['received_emaill']=m.received_emaill
        m_dict['received_hardcopy']=m.received_hardcopy
        m_dict['education']=m.education
        m_dict['work_experience']=m.work_experience
        try:
            m_dict['agent']=m.agent
        except:
            m_dict['agent']=''
        try:
            m_dict['furtherinterest']=m.furtherinterest
        except:
            m_dict['furtherinterest']=''
        try:
            m_dict['projects']=m.projects
        except:
            m_dict['projects']=''
        m_dict['status']=m.status
        m_dict['attendsess']=m.attendsess
        m_dict['last_contact']=m.last_contact
        fu_list=Follow_up.objects.filter(members=m).order_by('-timeline')[:1]
        for fu in fu_list:
            m_dict['fu']=fu
        if m_dict['status']!='7':
        
            today=str(today)
            toy=today[:4]
            tom=today[5:7]
            tod=today[8:10]
            if m.last_allocate:
                lastday=str(m.last_allocate)
            else:
                lastday=str(m.last_contact)
            toy2=lastday[:4]
            tom2=lastday[5:7]
            tod2=lastday[8:10]
            m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
            try:
                bedays=(datetime.datetime(int(toy),int(tom),int(tod))-datetime.datetime(int(toy2),int(tom2),int(tod2))).days
            except:
                bedays=1000
            bedays=int(bedays)
            m_dict['bedays']=bedays
            if bedays>90 and bedays<=120:
                #超过3个月未联系的,灰色
                m_dict['isgray']=1
            if bedays>120 and m_dict['interlevel']!='4':
                m_dict['isblack']=1

            if bedays>30 and bedays<=60:
                if m_dict['interlevel']=='0' or m_dict['interlevel']=='3' or m_dict['interlevel']=='4':
                #在過去一個月沒有連絡, 而Inter Level為 NC, NI, NT的人員
                    m_dict['isgray']=1

            if bedays>60:
                if m_dict['interlevel']=='0' or m_dict['interlevel']=='3':
                #在過去两個月沒有連絡, 而Inter Level為 NC, NI的人員
                    m_dict['isblack']=1
            if m_dict['isgray'] or m_dict['isblack']:
                m_dict['othercolor']=1
        m_dict['follow_remark']=nf.remark
        apage_list.append(m_dict)
    #####################################


    for m in curPage.object_list:
        m_dict={}
        if m.id not in inpage_list:
            m_dict['id']=m.id
            m_dict['is_today_follow']=0
            try:
                m_dict['salesperson']=m.salesperson
            except:
                m_dict['salesperson']=''
            m_dict['interlevel']=m.interlevel
            m_dict['name']=m.name
            m_dict['job_title']=m.job_title
            m_dict['company']=m.company
            m_dict['tel_h']=m.tel_h
            m_dict['tel_o']=m.tel_o
            m_dict['tel_m']=m.tel_m
            m_dict['email']=m.email
            m_dict['address']=m.address
            m_dict['regtime']=m.regtime
            m_dict['received_emaill']=m.received_emaill
            m_dict['received_hardcopy']=m.received_hardcopy
            m_dict['education']=m.education
            m_dict['work_experience']=m.work_experience
            try:
                m_dict['agent']=m.agent
            except:
                m_dict['agent']=''
            try:
                m_dict['furtherinterest']=m.furtherinterest
            except:
                m_dict['furtherinterest']=''
            try:
                m_dict['projects']=m.projects
            except:
                m_dict['projects']=''
            m_dict['status']=m.status
            m_dict['attendsess']=m.attendsess
            m_dict['last_contact']=m.last_contact
            fu_list=Follow_up.objects.filter(members=m).order_by('-timeline')[:1]
            for fu in fu_list:
                m_dict['fu']=fu
            if m_dict['status']!='7':
            
                today=str(today)
                toy=today[:4]
                tom=today[5:7]
                tod=today[8:10]
                if m.last_allocate:
                    lastday=str(m.last_allocate)
                else:
                    lastday=str(m.last_contact)
                toy2=lastday[:4]
                tom2=lastday[5:7]
                tod2=lastday[8:10]
                m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
                try:
                    bedays=(datetime.datetime(int(toy),int(tom),int(tod))-datetime.datetime(int(toy2),int(tom2),int(tod2))).days
                except:
                    bedays=1000
                bedays=int(bedays)
                m_dict['bedays']=bedays
                if bedays>90 and bedays<=120:
                    #超过3个月未联系的,灰色
                    m_dict['isgray']=1
                if bedays>120 and m_dict['interlevel']!='4':
                    m_dict['isblack']=1

                if bedays>30 and bedays<=60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3' or m_dict['interlevel']=='4':
                    #在過去一個月沒有連絡, 而Inter Level為 NC, NI, NT的人員
                        m_dict['isgray']=1

                if bedays>60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3':
                    #在過去两個月沒有連絡, 而Inter Level為 NC, NI的人員
                        m_dict['isblack']=1
                if m_dict['isgray'] or m_dict['isblack']:
                    m_dict['othercolor']=1
            m_dict['follow_remark']=''
            apage_list.append(m_dict)


    #except:
    #    raise
        #return HttpResponseRedirect('/ulist')
    return render_to_response('ulist.html',{
    'nf_list':nf_list,
    'p_id':int(p_id),
    'paginator':paginator,
    'members_list':apage_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': curPage.has_next(),
    'has_previous': curPage.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages+1)[1:],
    'hits' : paginator.count,
    'level':request.session['level'],
    'project_list':project_list,
    'agent_list':agent_list,
    'level':request.session['level'],
    'is_p':is_p
    })

"""查看用户详细信息"""
def uinfo (request,m_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    members = get_object_or_404(Members, pk=m_id)
    return render_to_response('edit_u.html',{'members': members,'act':'show'})

"""调用修改显示页"""
def edit_u(request, m_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    
#        salesid=minfo.salesperson_id
#        if request.session['id']!=salesid:
#            return HttpResponseRedirect('/')
    back_url=request.META.get('HTTP_REFERER','/ulist/')
    members = get_object_or_404(Members, pk=m_id)
    agent = Agent.objects.order_by('name')
    pj = Projects.objects.order_by('id')
    fi = Furtherinterest.objects.order_by('id')
    sales = Salesperson.objects.order_by('id')
    """查询其FOLLOW-UP"""
    f_object=Follow_up.objects.filter(members__id=m_id).order_by('id')
    """查询其同时报了其它项目的FOLLOW-UP"""
    otherproject_list=[]
    other_fl_list=[]
    try:
        otherproject_list=Members.objects.filter(is_removed=0,name=members.name,samecode=members.samecode,samecode__gt='').exclude(id=m_id).order_by('id')
        for tm in otherproject_list:
            t_dict={}
            ff_object=Follow_up.objects.filter(members=tm).order_by('id')
            try:
                t_dict['project']=tm.projects
                t_dict['sales']=tm.salesperson
                t_dict['flist']=ff_object
                other_fl_list.append(t_dict)
            except:
                pass
    except:
        pass
    #Next Follow Up Date Info
    is_deal=request.REQUEST.get('is_deal',"")
    try:
        next_follow_date_obj=Next_Follow_Date.objects.get(member=members,is_removed=0)
        if is_deal:
            is_deal=int(is_deal)
            next_follow_date_obj.is_deal=1
            next_follow_date_obj.save()
    except:
        next_follow_date_obj=''



    #查sales record不同人員的跟進紀綠
    sr_list=[]
    sr_list=Sales_record.objects.filter(members=members).order_by('id')
    today=datetime.date.today()
    today=str(today)
    if not sr_list:
        first_sales_id=members.salesperson_id
        try:
            first_sales_id=int(first_sales_id)
        except:
            first_sales_id=0
        if first_sales_id!=0:
            try:
                first_sales_obj=Salesperson.objects.get(pk=first_sales_id)
            except:
                first_sales_obj=''
            sr_list=[]
            if first_sales_obj:
                sr_dict={}
                sr_dict['id']=first_sales_obj.id
                sr_dict['salesperson']=first_sales_obj
                sr_dict['starttime']=str(members.regtime)[:10]
                sr_dict['endtime']=today
                sr_list.append(sr_dict)
            else:
                pass
    salesgroup = Salesperson_groups.objects.order_by('id')  #add sales group
    return render_to_response('edit_u.html',{'members': members,'act':'edit','f_object':f_object,'next_follow_date_obj':next_follow_date_obj,'agent':agent,'fi':fi,'pj':pj,'sales':sales,'level':request.session['level'],'back_url':back_url,'sr_list':sr_list,'today':today,'otherproject_list':otherproject_list,'other_fl_list':other_fl_list,'salesgroup':salesgroup})


"""删除用户"""
def del_u (request,m_id=""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    """操作者为SALES时,先检测此用户是否为他本人添加"""
    if request.session['level']!="administrators":
        minfo=Members.objects.get(pk=m_id)
        salesid=minfo.salesperson_id
        if request.session['id']!=salesid:
            return HttpResponseRedirect('/')
    #Members.objects.filter(pk=m_id).delete()
    minfo=Members.objects.get(pk=m_id)
    minfo.is_removed=1
    minfo.save()
    try:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
    except:
        return HttpResponseRedirect('/ulist/')


"""更改用户status"""
def changestatus(request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.META.get('HTTP_X_REQUESTED_WITH','').lower() == 'xmlhttprequest':
        id=request.REQUEST.get('id',"")
        status=request.REQUEST.get('value','0')
        if id:
            try:
                member=Members.objects.get(pk=int(id))
                member_obj=member
                member.status=status
                member.last_contact=datetime.datetime.now()
                member.save()
                finfo=Follow_up(
                status=status,
                members_id=id,
                )
                finfo.save()
                #如果STATUS为Enrolled则将其添加到student表
                """
                if status=='7':
                    try:
                        student = Student.objects.get(member=member_obj)
                    except:
                        student = Student(
                        name_en=member_obj.name,
                        name_ch='',
                        tel_h=member_obj.tel_h,
                        tel_o=member_obj.tel_o,
                        tel_m=member_obj.tel_m,
                        email=member_obj.email,
                        address=member_obj.address,
                        program=member_obj.projects,
                        agent=member_obj.agent,
                        member=member_obj,
                        referee=member_obj,
                        salesperson=member_obj.salesperson,
                        applytime=member_obj.regtime,
                        application_date='1900-01-01',
                        acceptance_date='1900-01-01',
                        start_date='1900-01-01',
                        birthday_date='1900-01-01',
                        )
                        student.save()
                        #return HttpResponse('errxx')
                """
                return HttpResponse('ok')
            except:
                return HttpResponse('error1')
        else:
            return HttpResponse('error2')
    else:
        return HttpResponse('there is something wrong')

"""更改用户level"""
def changelevel(request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.META.get('HTTP_X_REQUESTED_WITH','').lower() == 'xmlhttprequest':
        id=request.REQUEST.get('id',"")
        interlevel=request.REQUEST.get('value','0')
        if id:
            try:
                member=Members.objects.get(pk=int(id))
                member.interlevel=interlevel
                member.save()
                return HttpResponse('ok')
            except:
                return HttpResponse('error')
        else:
            return HttpResponse('error')
    else:
        return HttpResponse('there is something wrong')

"""用户查找"""
def search (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')
    is_p=''
    if request.method == 'GET':
        page=int(request.GET.get('page','1'))
        p_id=request.GET.get('p_id','0')
        is_p=''
        try:
            p_id=int(p_id)
        except:
            pass
        """
        try:
            p_id=request.session['program']
            is_p='y'
        except:
            p_id=request.GET.get('p_id','0')
            is_p=''
        """
        a_id=request.GET.get('a_id','0')
        sales=request.GET.get('sales','')
        name=request.GET.get('name','')
        tel=request.GET.get('tel','')
        followupremark=request.GET.get('followupremark','')
        email=request.GET.get('email','')
        interlevel=request.GET.get('interlevel','all')
        status=request.GET.get('status','all')
        start_date=request.GET.get('start_date','begin')
        end_date=request.GET.get('end_date','now')
        last_contact = request.GET.get('last_contact','none')
        members = Members.objects.filter(is_removed=0)
        group = request.session['group']
        sid = request.session['id']
        if start_date == 'begin' and end_date =='now':
            pass
        elif start_date =='begin' and end_date != 'now':
            members=members.filter(regtime__lte=end_date)
        elif start_date != 'begin' and end_date =='now':
            members=members.filter(regtime__gte=start_date)
        else:
            members=members.filter(regtime__range=(start_date, end_date))

        if p_id !=0:
            members=members.filter(projects__pk=int(p_id))
        if a_id !='0':
            members=members.filter(agent__pk=int(a_id))
        from django.db.models import Q
        if name:
            nameup=name.capitalize()
            members=members.filter(Q(name__icontains=name)|Q(name__icontains=nameup))
        if tel:
            members=members.filter(Q(tel_h__contains=tel)|Q(tel_o__contains=tel)|Q(tel_m__contains=tel))
        if email:
            emailup=email.capitalize()
            emailda=email.upper()
            emaillower=email.lower()
            members=members.filter(Q(email__icontains=email)|Q(email__icontains=emailup)|Q(email__contains=emailda)|Q(email__contains=emaillower))
        if interlevel !='all':
            members=members.filter(interlevel=interlevel)
        if status != 'all':
            members=members.filter(status=status)
#        if request.session['level']=='sales':
#            members=members.filter(salesperson__id=request.session['id'])
#        else:
        if sales:
            salesup=sales.capitalize()
            members=members.filter(Q(salesperson__name__icontains=sales)|Q(salesperson__name__icontains=salesup))
        import datetime
        if last_contact != 'none':
            nowtime = datetime.datetime.now()
            members=members.filter(last_contact__lte=last_contact)
        if group>0: #根据用户组ID来显示相应潜客数据
            #if request.session['level']!="administrators":
                #members = members.filter(Q(salesperson =sid)|(Q(salesperson =0)&Q(men_area = group)))
            #else:
                members = members.filter(men_area = group)
        
        members=members.order_by('-regtime')
        #members=members.order_by('name')

        m_tmp_list=[]
        havefr=''
        if followupremark!='':
            for m in members:
                fu_list=Follow_up.objects.filter(members=m,remarks__contains=followupremark)[:1]
                if fu_list:
                    m_tmp_list.append(m)
            havefr=1

        members_list=apage_list=temp_list=[]
        today=datetime.date.today()
        #startid=30*(int(page)-1)
        #endid=30*int(page)
        #temp_list=members[startid:endid]
        if havefr=='':
            paginator=Paginator(members,30)
        else:
            paginator=Paginator(m_tmp_list,30)
        page=int(page)
        curPage = paginator.page(page)
        
        ##next follow date #########################################
        #today's next follow date list
        today=datetime.date.today()
        nf_list=[]

        if request.session['level']=='administrators':
            nf_list = Next_Follow_Date.objects.filter(is_removed=0,follow_date=today,is_deal=0).order_by('follow_date')
            if sales:
                try:
                    sales_obj=Salesperson.objects.get(name=sales)
                    nf_list=nf_list.filter(member__salesperson=sales_obj)
                except:
                    pass
        else:
            try:
                sales_obj=Salesperson.objects.get(pk=request.session['id'])
                nf_list=Next_Follow_Date.objects.filter(member__salesperson=sales_obj,is_removed=0,is_deal=0,follow_date=today).order_by('follow_date')
            except:
                pass
            
        p_obj=''
        if p_id!=0:
            try:
                p_obj=Projects.objects.get(pk=p_id)
                nf_list=nf_list.filter(member__projects=p_obj)
            except:
                p_obj=''

        inpage_list=[]
        for nf in nf_list:
            m=nf.member
            m_dict={}
            m_dict['id']=m.id
            inpage_list.append(m.id)
            m_dict['is_today_follow']=1
            try:
                m_dict['salesperson']=m.salesperson
            except:
                m_dict['salesperson']=''
            m_dict['interlevel']=m.interlevel
            m_dict['name']=m.name
            m_dict['job_title']=m.job_title
            m_dict['company']=m.company
            m_dict['tel_h']=m.tel_h
            m_dict['tel_o']=m.tel_o
            m_dict['tel_m']=m.tel_m
            m_dict['email']=m.email
            m_dict['address']=m.address
            m_dict['regtime']=m.regtime
            m_dict['received_emaill']=m.received_emaill
            m_dict['received_hardcopy']=m.received_hardcopy
            m_dict['education']=m.education
            m_dict['work_experience']=m.work_experience
            try:
                m_dict['agent']=m.agent
            except:
                m_dict['agent']=''
            try:
                m_dict['furtherinterest']=m.furtherinterest
            except:
                m_dict['furtherinterest']=''
            try:
                m_dict['projects']=m.projects
            except:
                m_dict['projects']=''
            m_dict['status']=m.status
            m_dict['attendsess']=m.attendsess
            m_dict['last_contact']=m.last_contact
            fu_list=Follow_up.objects.filter(members=m).order_by('-timeline')[:1]
            for fu in fu_list:
                m_dict['fu']=fu
            if m_dict['status']!='7':
            
                today=str(today)
                toy=today[:4]
                tom=today[5:7]
                tod=today[8:10]
                if m.last_allocate:
                    lastday=str(m.last_allocate)
                else:
                    lastday=str(m.last_contact)
                toy2=lastday[:4]
                tom2=lastday[5:7]
                tod2=lastday[8:10]
                m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
                try:
                    bedays=(datetime.datetime(int(toy),int(tom),int(tod))-datetime.datetime(int(toy2),int(tom2),int(tod2))).days
                except:
                    bedays=1000
                bedays=int(bedays)
                m_dict['bedays']=bedays
                if bedays>90 and bedays<=120:
                    #超过3个月未联系的,灰色
                    m_dict['isgray']=1
                if bedays>120 and m_dict['interlevel']!='4':
                    m_dict['isblack']=1

                if bedays>30 and bedays<=60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3' or m_dict['interlevel']=='4':
                    #在過去一個月沒有連絡, 而Inter Level為 NC, NI, NT的人員
                        m_dict['isgray']=1

                if bedays>60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3':
                    #在過去两個月沒有連絡, 而Inter Level為 NC, NI的人員
                        m_dict['isblack']=1
                if m_dict['isgray'] or m_dict['isblack']:
                    m_dict['othercolor']=1
            m_dict['follow_remark']=nf.remark
            apage_list.append(m_dict)
        #####################################

        #members_list=members
        for m in curPage.object_list:
            m_dict={}
            if m.id not in inpage_list:
                m_dict['id']=m.id
                m_dict['is_today_follow']=0
                m_dict['id']=m.id
                try:
                    m_dict['salesperson']=m.salesperson
                except:
                    m_dict['salesperson']=''
                m_dict['interlevel']=m.interlevel
                m_dict['name']=m.name
                m_dict['job_title']=m.job_title
                m_dict['company']=m.company
                m_dict['tel_h']=m.tel_h
                m_dict['tel_o']=m.tel_o
                m_dict['tel_m']=m.tel_m
                m_dict['email']=m.email
                m_dict['address']=m.address
                m_dict['regtime']=m.regtime
                m_dict['received_emaill']=m.received_emaill
                m_dict['received_hardcopy']=m.received_hardcopy
                m_dict['education']=m.education
                m_dict['work_experience']=m.work_experience
                try:
                    m_dict['agent']=m.agent
                except:
                    m_dict['agent']=''
                try:
                    m_dict['furtherinterest']=m.furtherinterest
                except:
                    m_dict['furtherinterest']=''
                try:
                    m_dict['projects']=m.projects
                except:
                    m_dict['projects']=''
                m_dict['status']=m.status
                m_dict['attendsess']=m.attendsess
                m_dict['last_contact']=m.last_contact
                fu_list=Follow_up.objects.filter(members=m).order_by('-timeline')[:1]
                for fu in fu_list:
                    m_dict['fu']=fu
                today=str(today)
                toy=today[:4]
                tom=today[5:7]
                tod=today[8:10]
                if m.last_allocate:
                    lastday=str(m.last_allocate)
                else:
                    lastday=str(m.last_contact)
                #lastday=str(m.last_contact)
                toy2=lastday[:4]
                tom2=lastday[5:7]
                tod2=lastday[8:10]
                m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
                try:
                    bedays=(datetime.datetime(int(toy),int(tom),int(tod))-datetime.datetime(int(toy2),int(tom2),int(tod2))).days
                except:
                    bedays=1000
                bedays=int(bedays)
                if bedays>90 and bedays<=120 and m_dict['interlevel']!='4':
                    #超过3个月未联系的,灰色
                    m_dict['isgray']=1
                if bedays>120 and m_dict['interlevel']!='4':
                    m_dict['isblack']=1

                if bedays>30 and bedays<=60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3' or m_dict['interlevel']=='4':
                    #在過去一個月沒有連絡, 而Inter Level為 NC, NI, NT的人員
                        m_dict['isgray']=1

                if bedays>60:
                    if m_dict['interlevel']=='0' or m_dict['interlevel']=='3':
                    #在過去一個月沒有連絡, 而Inter Level為 NC, NI的人員
                        m_dict['isblack']=1
                if m_dict['isgray'] or m_dict['isblack']:
                    m_dict['othercolor']=1
                m_dict['follow_remark']=''
                apage_list.append(m_dict)


        #try:
            #page=int(page)
            #if page > paginator.pages:
            #    page=paginator.pages
            #if page < 1:
            #    page=1
        #except:
            #return HttpResponseRedirect('/ulist')
        return render_to_response('ulist.html',{
        'paginator':paginator,
        'members_list':apage_list,
        'is_paginated': paginator.num_pages > 1,
        'has_next': curPage.has_next(),
        'has_previous': curPage.has_previous(),
        'current_page': page,
        'next_page': page + 1,
        'previous_page': page - 1,
        'pages': paginator.num_pages,
        'page_numbers': range(paginator.num_pages+1)[1:],
        'hits' : paginator.count,
        'level':request.session['level'],
        'issearch':"y",
        'p_id':int(p_id),
        'a_id':int(a_id),
        'sales':sales,
        'name':name,
        'email':email,
        'followupremark':followupremark,
        'tel':tel,
        'interlevel':interlevel,
        'status':status,
        'project_list':project_list,
        'agent_list':agent_list,
        'start_date':start_date,
        'end_date':end_date,
        'last_contact':last_contact,
        'is_p':'',
        })

"""邮件地址"""
def getmail (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')

    #agent_list = Agent.objects.order_by('id')
    #project_list = Projects.objects.order_by('id')
    members=getmember(request)
    from django.conf import settings
    maxrow=settings.MAX_ROW
    #maxrow=2000
    import xlwt as pycel
    if len(members)>maxrow:
        query=request.META['QUERY_STRING']
        page=len(members)/maxrow
        if page*maxrow<len(members):
            page+=1
        output="""Please download the following excel file (Each file up to 2,000 records)<br/>"""
        for x in range(1,page+1):
            output+="""<a href='/u/mail2/?"""+query+"""&page="""+str(x)+"""'>email"""+str(x)+""".xls</a><br/>"""
        return HttpResponse(output)
    else:
        #wb = pycel.Workbook()
        wb = pycel.Workbook(encoding='utf-8')
        ws = wb.add_sheet('email address')
        ws.write(0,0,'name')
        ws.write(0,1,'email')
        rrow=1
        for x in range(0,len(members)):
            try:
                ws.write(rrow,0,members[x].name)
                ws.write(rrow,1,members[x].email)
                rrow+=1
            except:
                pass
        try:
            wb.save(settings.WEB_ROOT+'/static/file/email.xls')
        except:
            errinfo=str(settings.WEB_ROOT)+"/static/file/email.xls IO error"
            return HttpResponse(errinfo)
        response = HttpResponse(mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=%s' % 'email.xls'
        fp=open(settings.WEB_ROOT+'/static/file/email.xls')
        response.write(fp.read())
        return response
"""邮件2"""
def getmail2(request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    members=getmember(request)
    from django.conf import settings
    maxrow=settings.MAX_ROW
    #maxrow=2000
    page=int(request.GET.get('page','1'))
    num=len(members)/maxrow
    if num*maxrow<len(members):
        num+=1
    if page>num:
        page=num
    mmin=(page-1)*maxrow
    mmax=page*maxrow
    if page == num:
        mmax=len(members)
    try:
        import xlwt as pycel
    except:
        return HttpResponse('import error')
    wb = pycel.Workbook(encoding='utf-8')
    ws = wb.add_sheet('email address')
    ws.write(0,0,'name')
    ws.write(0,1,'email')
    rrow=1
    for x in range(mmin,mmax):
        try:
            ws.write(rrow,0,members[x].name)
            ws.write(rrow,1,members[x].email)
            rrow+=1
        except:
            pass
    #fname=now_path+'/static/file/email'+str(page)+'.xls'
    fname=settings.WEB_ROOT+'/static/file/email'+str(page)+'.xls'
    try:
        wb.save(fname)
    except:
        return HttpResponse('IO error')
    response = HttpResponse(mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s' % ('email'+str(page)+'.xls')
    fp=open(settings.WEB_ROOT+'/static/file/email'+str(page)+'.xls')
    response.write(fp.read())
    return response

"""邮递地址"""
def getpost (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')

    #agent_list = Agent.objects.order_by('id')
    #project_list = Projects.objects.order_by('id')
    members=getmember(request)
    from django.conf import settings
    maxrow=settings.MAX_ROW
    #maxrow=100
    import xlwt as pycel
    if len(members)>maxrow:
        query=request.META['QUERY_STRING']
        page=len(members)/maxrow
        if page*maxrow<len(members):
            page+=1
        output="""Please download the following excel file (Each file up to 2,000 records)<br/>"""
        for x in range(1,page+1):
            output+="""<a href='/u/post2/?"""+query+"""&page="""+str(x)+"""'>post"""+str(x)+""".xls</a><br/>"""
        return HttpResponse(output)
    else:
        wb = pycel.Workbook(encoding='utf-8')
        ws = wb.add_sheet('postal address')
        ws.write(0,0,'name')
        ws.write(0,1,'post')
        rrow=1
        for x in range(0,len(members)):
            try:
                ws.write(rrow,0,members[x].name)
                ws.write(rrow,1,members[x].address)
                rrow+=1
            except:
                pass
        try:
            wb.save(settings.WEB_ROOT+'/static/file/address.xls')
        except:
            return HttpResponse('IO error')
        response = HttpResponse(mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=%s' % 'address.xls'
        fp=open(settings.WEB_ROOT+'/static/file/address.xls')
        response.write(fp.read())
        return response
"""邮递2"""
def getpost2(request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    members=getmember(request)
    from django.conf import settings
    maxrow=settings.MAX_ROW
    #maxrow=100
    page=int(request.GET.get('page','1'))
    num=len(members)/maxrow
    if num*maxrow<len(members):
        num+=1
    if page>num:
        page=num
    mmin=(page-1)*maxrow
    mmax=page*maxrow
    if page == num:
        mmax=len(members)
    import xlwt as pycel
    wb = pycel.Workbook(encoding='utf-8')
    ws = wb.add_sheet('postal address')
    ws.write(0,0,'name')
    ws.write(0,1,'address')
    rrow=1
    for x in range(mmin,mmax):
        try:
            ws.write(rrow,0,members[x].name)
            ws.write(rrow,1,members[x].address)
            rrow+=1
        except:
            pass
    fname=settings.WEB_ROOT+'/static/file/address'+str(page)+'.xls'
    try:
        wb.save(fname)
    except:
        return HttpResponse('IO error')
    response = HttpResponse(mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s' % ('address'+str(page)+'.xls')
    fp=open(settings.WEB_ROOT+'/static/file/address'+str(page)+'.xls')
    response.write(fp.read())
    return response

"""查询用户"""
def getmember(request):
    page=int(request.GET.get('page','1'))
    is_p=''
    """
    try:
        p_id=request.session['program']
        is_p='y'
    except:
        p_id=request.GET.get('p_id','0')
        is_p=''
    """
    p_id=request.GET.get('p_id','0')
    a_id=request.GET.get('a_id','0')
    sales=request.GET.get('sales','')
    name=request.GET.get('name','')
    tel=request.GET.get('tel','')
    email=request.GET.get('email','')
    interlevel=request.GET.get('interlevel','all')
    status=request.GET.get('status','all')
    start_date=request.GET.get('start_date','begin')
    end_date=request.GET.get('end_date','now')
    last_contact = request.GET.get('last_contact','none')
    statused=request.GET.get('statused','0')
    followupremark=request.GET.get('followupremark','')
    try:
        statused=int(statused)
    except:
        statused=0
    members = Members.objects.filter(is_removed=0)
    if start_date == 'begin' and end_date =='now':
        pass
    elif start_date =='begin' and end_date != 'now':
        members=members.filter(regtime__lte=end_date)
    elif start_date != 'begin' and end_date =='now':
        members=members.filter(regtime__gte=start_date)
    else:
        members=members.filter(regtime__range=(start_date, end_date))

    if p_id !='0':
        members=members.filter(projects__pk=int(p_id))
    if a_id !='0':
        members=members.filter(agent__pk=int(a_id))
    from django.db.models import Q
    if name:
        nameup=name.capitalize()
        members=members.filter(Q(name__icontains=name)|Q(name__icontains=nameup))
    if tel:
        members=members.filter(Q(tel_h__contains=tel)|Q(tel_o__contains=tel)|Q(tel_m__contains=tel))
    if email:
        members=members.filter(email__icontains=email)
    if interlevel !='all':
        members=members.filter(interlevel=interlevel)
    if status != 'all':
        members=members.filter(status=status)
    if statused==0:
        members=members.filter().exclude(status=7)
#        if request.session['level']=='sales':
#            members=members.filter(salesperson__id=request.session['id'])
#        else:
    if sales:
        members=members.filter(salesperson__name=sales)
    if last_contact != 'none':
        members=members.filter(last_contact__lte=last_contact)
    
    members=members.order_by('-id')

    m_tmp_list=[]
    havefr=''
    if followupremark!='':
        for m in members:
            fu_list=Follow_up.objects.filter(members=m,remarks__contains=followupremark)[:1]
            if fu_list:
                m_tmp_list.append(m)
        havefr=1
    if havefr==1:
        return m_tmp_list
    else:
        return members


#把客户转为学员
def add_to_student (request,m_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')

    try:
        member=Members.objects.get(pk=int(m_id))
        member_obj=member
        
        try:
            student = Student.objects.get(member=member_obj)
        except:
            student = Student(
            name_en=member_obj.name,
            fullname=member_obj.name,
            name_ch='',
            tel_h=member_obj.tel_h,
            tel_o=member_obj.tel_o,
            tel_m=member_obj.tel_m,
            email=member_obj.email,
            address=member_obj.address,
            program=member_obj.projects,
            agent=member_obj.agent,
            member=member_obj,
            referee=member_obj,
            salesperson=member_obj.salesperson,
            applytime=member_obj.regtime,
            application_date='1900-01-01',
            acceptance_date='1900-01-01',
            start_date='1900-01-01',
            birthday_date='1900-01-01',
            )
            student.save()
        
    except:
        pass

    return HttpResponseRedirect("/v2/stusearch/?page=1&p_id=0&a_id=0&sales=&name=&tel=&email=&start_date=begin&end_date=now")